//
//  LoginViewController.swift
//  ezyform
//
//  Created by FengMoennig on 12/28/15.
//  Copyright © 2015 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import SnapKit
import DaisyNet
class LoginViewController: BaseViewController {
    var label : BaseLabel = BaseLabel()
    var lableHeight: CGFloat = 15.0
    var autoToFavoriteLoginMethod: Bool = false//是否自动跳转到Login Method界面
    let customView = LoginView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        //开启了跳转到最佳的login method
        if self.autoToFavoriteLoginMethod {
            self.toFavoriteLoginMethod()
        }else{//不跳转时，默认是指为password
            //Logout时，设置为password
            APPConfig.loginInfo.currentLoginMethod = .password
        }
        NotificationCenter.default.addObserver(self, selector: #selector(refreshMoreLoginMethod), name: NSNotification.Name(rawValue: "me.loginmethod.setting"), object: nil)
        
    }
    func initUI(){
        self.view = self.customView
        self.customView.emailTextField.delegate = self
        self.customView.pwdTextField.delegate = self
        
        //set default data
        self.customView.loginBtn.addTarget(self, action: #selector(loginBtnClick), for: UIControl.Event.touchUpInside)
        //
        self.customView.emailTextField.text = APPConfig.loginInfo.email
        //set default data
        self.customView.registerBtn.addTarget(self, action: #selector(registerBtnClick), for: UIControl.Event.touchUpInside)
        //set default data
        self.customView.forgotPwdBtn.addTarget(self, action: #selector(forgotPwdBtnClick), for: UIControl.Event.touchUpInside)
        //more option
        self.customView.loginOptionsMenuView.selectTypeClosure = {[weak self] (type) in
            guard let strongSelf = self else { return }
            APPConfig.loginInfo.currentLoginMethod = type
            strongSelf.toLoginMoreMethodVC()
        }
    }
    @objc
    func refreshMoreLoginMethod(){
        let list = LoginMethodServcie().getOtherLoginMethod(.password)
        //
        if list.count == 0 {//如果当前选择是0，就remove 所有的more options
            self.customView.removeMoreLoginOption()
        }else if list.count > 0{//如果大于0个options，menu view如果显示，要刷新
            if let _ = self.customView.loginOptionsMenuView.superview{
                self.customView.loginOptionsMenuView.initMenuUI()
            }
        }
    }
    func toFavoriteLoginMethod(){
        let list = LoginMethodServcie().getOtherLoginMethod(.password)
        if list.contains(.faceID) {
            APPConfig.loginInfo.currentLoginMethod = .faceID
        }else if list.contains(.touchID) {
            APPConfig.loginInfo.currentLoginMethod = .touchID
        }else if list.contains(.gesture){
            APPConfig.loginInfo.currentLoginMethod = .gesture
        }
        if list.count > 0{
            self.toLoginMoreMethodVC()
        }
    }
    
    private func toLoginMoreMethodVC(){
        let vc = LoginMoreOptionsViewController()
        vc.modalPresentationStyle = .overFullScreen
        vc.refreshMoreOptionsBtnClosure = { [weak self] in
            guard let strongself = self else { return }
            strongself.customView.addMoreLoginOptionBtn()
            strongself.customView.pwdTextField.becomeFirstResponder()
        }
        self.present(vc, animated: true)
    }
    @objc
    func registerBtnClick(){
        let vc = RegisterViewController()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    @objc
    func forgotPwdBtnClick(){
        //email不能为空，且符合邮件格式正则表达式
        if let email = self.customView.emailTextField.text, email != "" && Tool().isValidEmail(emailStr: email) {
            Tool().showAlertViewWithTwoBtns(message: "Send password reset email to " + email,cancelStr: R.string.localizable.cancel(), confirmStr: "Send Email",noClosure: nil) {
                if  Connectivity.isConnectedToInternet {
                    let viewModel = LoginService()
                    viewModel.setBlockAfterNetwork({ (result , _) -> Void in
                        ModelViewUtil.shared.hideLoadingView()
                        if let msg = result as? String {
                            Tool().showAlertViewWithOneBtn(message: msg)
                        }
                    }) {(code, error) -> Void in
                        ModelViewUtil.shared.hideLoadingView()
                        Tool().showErrorInfo(code, error)
                    }
                    //add Loading view
                    ModelViewUtil.shared.showLoadingView("Sending...")
                    //
                    viewModel.forgotPwd(email: email)
                }else{
                    Tool().showFailureInfo()
                }
            }
            
        }else{
            Tool().showAlertViewWithOneBtn(message: "Email is not valid.Provide a valid email for reset password instructions.")
        }
    }
    
    @objc
    func loginBtnClick() {
        let model = self.customView.getLoginParams()
        if  Connectivity.isConnectedToInternet {
            let viewModel = LoginService()
            viewModel.setBlockAfterNetwork({ (result , _) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                DaisyNet.removeAllCache(completion: {_ in })//清空所有数据
                //1.登录后，保存下已显示过引导页
                Tool().setValueOfUserDefaults(true, key: APPConfig.ShowStartViewKey)
                //拉取下Accreditation Number,用户判断当前用户是否是Installer
                SystemInfoService.shared().loadMyInformation()
                LoginMethodServcie().initRootVC()
            }) {(code, error) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                Tool().showErrorInfo(code, error)
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("login.logining" , comment: ""))
            viewModel.login(model)
        }else{
            Tool().showFailureInfo()
        }
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    deinit {
        if self.isViewDidLoad {
            NotificationCenter.default.removeObserver(self)
        }
    }
}
extension LoginViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.customView.emailTextField {
            APPConfig.loginInfo.email = (textField.text ?? "").trimmingCharacters(in: .whitespaces).lowercased()
            self.customView.addMoreLoginOptionBtn()
        }
    }
    //return event on keyboard
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == self.customView.emailTextField {
            self.customView.pwdTextField.becomeFirstResponder()
        }else if textField == self.customView.pwdTextField {
            self.customView.pwdTextField.resignFirstResponder()
            self.loginBtnClick()
        }
        return true
    }
}

